package org.yray.sip.rtp.sender;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yray.sip.rtp.data.MediaWav;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.time.SendMediaSendTask;
import org.yray.sip.time.SendPacketTimer;
import org.yray.sip.utils.IcspBeanHolder;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;

@Service
@Slf4j
public class RtcpSender implements IRtcpSender{
    @Autowired
    private SendPacketTimer timer;
    /**
     *
     00005e0001077|c8ae170c7b8|0800|45|00   目的mac地址|源mac地址|0800代表使用IP4|代表版本4|固定00，此行数据不用理
     0058|8778|0000|c8|11|3c84|ac820d1f|      代表数据的总长度|Identification: 固定|offset固定|time to live固定|11代表udp协议|header checksum|源IP，172.130.13.31|
     aca8c84e|0fa1|6955|0044|e8a1|  目的IP172.168.200.78|源端口4001|目的端口26965|报文长度68|checksum|rtcp从这里开始，前面的数据都不用理
     81|c9|0007|452670d5      rtcp版本2固定81|c9代表类型201|长度|SSRC|
     00000000|00|000000|0000|0000|00000000|  Identification|fraction lost|cum lost|seq|high seq|jitter|
     00000000|00000000|81ca00064526  last timestamp|delay timestamp
     70d50110306661613361333037366665
     326436340000
     *
     */

    public void sendRR(SipServerContext sipServerContext, String callId)
    {
        SipSession session= IcspBeanHolder.getBean(ISipSessionCache.class).get(callId);
        if(session==null)
        {
            return;
        }
        byte[] rtcpMsg= ArrayUtils.addAll(RRPacket.builtRR(session.getSsrc()),RRPacket.builtSDES(session.getSsrc(),session.getCname()));
        sipServerContext.getUrtcpServerHandler().send(rtcpMsg,new InetSocketAddress(session.getSideRtcpIp(),session.getSideRtcpPort()));
        session.initTimeStamp();
        byte[] rtpMSg=RtpPacket.builtTs(session.getSsrc(),session.getRtpSeq(),session.getTimeStamp());
        sipServerContext.getUrtpServerHandler().send(rtpMSg,session.mySideRtpSender());
    }


    @Override
    public long sendRtp(String callId, String text, String speaker)  {
        long timeLen=1;
        SipSession session=IcspBeanHolder.getBean(ISipSessionCache.class).get(callId);
        if(session==null)
        {
            return timeLen;
        }
        String wavId= SecureUtil.md5(text);
        byte[] wavs= MediaWav.getWav(wavId,speaker);
        timeLen=sendPcm(wavs,session);
        return timeLen;

    }

    private long  sendPcm(byte[] wavs,SipSession session)
    {
        int timeStamp=session.getTimeStamp();
        int len=wavs.length/SipSession.PCMA_STEP_SIZE;
        long correction=SipSession.PCMA_STEP_TIME_LEN-session.getPtime()%SipSession.PCMA_STEP_TIME_LEN;
        long curr=System.currentTimeMillis();
        long time=0;
        int sentenceSn=session.incSentenceSnAndGet();
        log.info("sendPcm,{},{}",session.getCallId(),sentenceSn);
        for(int i=0;i<len;i++) {
            byte[] bsRtp = new byte[SipSession.PCMA_STEP_SIZE];
            System.arraycopy(wavs,i*SipSession.PCMA_STEP_SIZE,bsRtp,0,SipSession.PCMA_STEP_SIZE);
            byte[] sendPcms=RtpPacket.builtPcma(session.getSsrc(), session.getRtpSeq(), timeStamp, bsRtp);
            time=i*SipSession.PCMA_STEP_TIME_LEN+correction+curr;
            //time=(i*SipSession.PCMA_STEP_TIME_LEN+correction)*1000000+currNano;
            timer.add(new SendMediaSendTask(time,sendPcms,session.mySideRtpSender(),i,sentenceSn,session.getCallId()));
            timeStamp+=SipSession.PCMA_STEP_STAMP;
        }
        return len*SipSession.PCMA_STEP_TIME_LEN;
    }

    public static void main(String[] args) {
        System.out.println(SecureUtil.md5("正在转接中，请耐心等候，如等待时间过长，非常抱歉，请您先挂机，稍后我们客服人员会联系您，"));
    }
}
